package com.sky.service.impl;

import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.vo.OrderReportVO;
import com.sky.vo.SalesTop10ReportVO;
import com.sky.vo.TurnoverReportVO;
import com.sky.vo.UserReportVO;
import lombok.extern.java.Log;
import lombok.extern.slf4j.Slf4j;
import net.sf.jsqlparser.expression.DateTimeLiteralExpression;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
public class ReportServiceimpl implements ReportService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    UserMapper userMapper;
    @Override
    public TurnoverReportVO turnoverStatistics(LocalDate begin, LocalDate end) {
        // 计算从begin到end的每一天
        List<LocalDate> localDates = begintoEnd(begin, end);
        //根据每一天获取每一天的营业额  查询订单状态为以为完成的订单
        // 订单创建时间在[begin,end]
        List<Map<String, Object>> statistics = orderMapper.getStatistics(localDates, Orders.COMPLETED);
        // 处理日期列表，把 LocalDate 格式化为字符串
        List<String> datelist = statistics.stream()
                .map(map -> (java.sql.Date) map.get("order_date"))
                .filter(Objects::nonNull)
                .map(date -> date.toLocalDate().format(DateTimeFormatter.ISO_LOCAL_DATE))
                .collect(Collectors.toList());
        //todo 日期列表
        // 处理营业额列表，将金额转换为字符串
        List<String> turnoverList = statistics.stream()
                .map(map -> map.get("total_amount"))
                .filter(Objects::nonNull)
                .map(obj -> {
                    if (obj instanceof Number) {
                        return String.valueOf(((Number) obj).doubleValue());
                    }
                    return obj.toString();
                })
                .collect(Collectors.toList());
        log.info("原始数据：{} {}", turnoverList, datelist);
        // 使用修正后的 String.join 方法
        return TurnoverReportVO.builder()
                .dateList(String.join(",", datelist))
                .turnoverList(String.join(",", turnoverList))
                .build();
    }

    @Override
    public OrderReportVO ordersStatistics(LocalDate begin, LocalDate end) {
        List<LocalDate> localDates = begintoEnd(begin, end);
        //新建两个集合分别存储订单数据
        List<Integer> totalOrderCounts = new ArrayList<>();
        List<Integer> validOrderCounts = new ArrayList<>();
        for (LocalDate localDate : localDates) {
            log.info("查询{}的订单数据",localDate);
            Map map = new HashMap<>() ;
            map.put("orderDate",localDate);
            // 查询订单总数
            Integer totalOrderCount = orderMapper.getordersStatistics(map);
            if(totalOrderCount == null){
                totalOrderCount = 0;
            }

            // 查询订单有效数
            map.put("status",Orders.COMPLETED);
            Integer validOrderCount = orderMapper.getordersStatistics(map);
            if(validOrderCount == null){
                validOrderCount = 0;
            }
            totalOrderCounts.add(totalOrderCount);
            validOrderCounts.add(validOrderCount);

        }
        //获取有效订单数
        log.info("有效订单数：{}",validOrderCounts);
        Integer validOrderCountSum = validOrderCounts.stream()
                .reduce(0, Integer::sum); // 初始值为0，流为空时直接返回0
        //获取总订单数
        log.info("总订单数：{}",totalOrderCounts);
        Integer totalOrderCountSum = totalOrderCounts.stream()
                .reduce(0, Integer::sum);
        //获取订单完成率
        Double orderCompletionRate = 0.0;
        if (totalOrderCountSum != 0) {
            orderCompletionRate = validOrderCountSum.doubleValue() / totalOrderCountSum;
        }

        return OrderReportVO.builder()
                .dateList(String.join(",", localDates.stream().map(date -> date.format(DateTimeFormatter.ISO_LOCAL_DATE)).collect(Collectors.toList())))
                .orderCountList(String.join(",", totalOrderCounts.stream().map(String::valueOf).collect(Collectors.toList())))
                .validOrderCountList(String.join(",", validOrderCounts.stream().map(String::valueOf).collect(Collectors.toList())))
                .totalOrderCount(totalOrderCountSum)
                .validOrderCount(validOrderCountSum)
                .orderCompletionRate(orderCompletionRate)
                .build();


    }

    @Override
    public UserReportVO userStatistics(LocalDate begin, LocalDate end) {
        List<LocalDate> localDates = begintoEnd(begin, end);
        //新建两个集合分别存储用户数据
        List<Integer> totalUserList = new ArrayList<>();
        List<Integer> newUserList = new ArrayList<>();
        for (LocalDate localDate : localDates) {
            log.info("查询{}的用户数据",localDate);
            // 查询总用户数
          Integer totalUser =  userMapper.getUserStatistics(localDate);
          if(totalUser == null){
              totalUser = 0;
          }
          totalUserList.add(totalUser);
          // 查询新用户数
            Integer newUser = userMapper.getNewUserStatistics(localDate);
            if(newUser == null){
                newUser = 0;
            }
            newUserList.add(newUser);
        }
        return UserReportVO.builder()
                .dateList(String.join(",", localDates.stream().map(date -> date.format(DateTimeFormatter.ISO_LOCAL_DATE)).collect(Collectors.toList())))
                .totalUserList(String.join(",", totalUserList.stream().map(String::valueOf).collect(Collectors.toList())))
                .newUserList(String.join(",", newUserList.stream().map(String::valueOf).collect(Collectors.toList())))
                .build();
    }

    /**
     * 统计top10
     *
     **/
    @Override
    public SalesTop10ReportVO top10(LocalDate begin, LocalDate end) {

        // 获取top10
        List<Map<String, Object>> statistics = orderMapper.gettop10(begin, end);
        log.info("top10数据：{}",statistics);
        //处理数据
        List<String> nameList = statistics.stream()
                .map(map -> (String) map.get("name"))
                .collect(Collectors.toList());
        log.info("名称：{}",nameList);

        //处理数量
        // 处理数量（正确地将 BigDecimal 转换为 String）
        List<String> numberList = statistics.stream()
                .map(map -> ((BigDecimal) map.get("sum")).toString()) // 或者使用 toPlainString() 避免科学计数法
                .collect(Collectors.toList());
        log.info("数量：{}",numberList);


        return SalesTop10ReportVO.builder()
                .nameList(String.join(",", nameList))
                .numberList(String.join(",", numberList))
                .build();
    }

    /**
     * 统计天数
     *
     **/
    private static List<LocalDate> begintoEnd(LocalDate begin, LocalDate end) {
        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);
        while (!begin.equals(end)){
            begin = begin.plusDays(1);
            dateList.add(begin);
        }
        return dateList;
    }
}
